<script lang="ts" setup>
import type {Tag} from "@/components/types";
import { ref,watch } from 'vue'
import UIcon from "@/uni_modules/uview-plus/components/u-icon/u-icon.vue";
import UInput from "@/uni_modules/uview-plus/components/u--input/u--input.vue";
import UModal from "@/uni_modules/uview-plus/components/u-modal/u-modal.vue";

const props = withDefaults(defineProps<{
  tagList: Tag[],
  modelValue: Tag[]
}>(),{
  tagList(){
    return []
  },
  modelValue(){
    return []
  }
})
const emits = defineEmits<{
  (e: "update:modelValue", value: Tag[]):void
  (e: "insert", value: string, callback: (tag: Tag | null) => void): void
}>()
const selectTag = ref<Tag[]>([])

// tag子项点击事件
const handlerTagItemClick = (tag: Tag) => {
  // 判断点击项在选中列表中是否存在
  const findIndex = selectTag.value.findIndex(item => item.value === tag.value)
  // 不存在就添加进选中项
  if(findIndex === -1){
    selectTag.value.push(tag)
  }else{
    // 存在的话就从选中列表中删除
    selectTag.value.splice(findIndex, 1)
  }
  // 更新选中列表
  emits("update:modelValue", selectTag.value)
}

const insertText = ref<string>('')
// 弹窗显示状态
const show = ref(false)
const handlerConfirm = async () => {
  emits("insert", insertText.value, (tag: Tag | null): void => {
    if(tag){
      selectTag.value.push(tag)
      // 更新选中列表
      emits("update:modelValue", selectTag.value)
    }
    show.value = false;
  })
}
watch(() => props.modelValue,(newVal, oldVal) => {
  if(newVal !== oldVal){
    selectTag.value = newVal
  }
})
</script>

<template>
<view class="tag-select">
  <view class="tag-selected-box">
    <template v-for="(item,index) in selectTag" :key="index">
      <view @click="handlerTagItemClick(item)" class="tag-item active align-middle">{{item.label}}</view>
    </template>
    <view class="tag-item inline-block align-middle" @click="show = true">
      <u-icon class="inline-block" name="plus" color="#2979ff"/>
      <u-modal :show="show" @confirm="handlerConfirm" @cancel="show = false" :asyncClose="true" show-cancel-button>
        <u-input v-model="insertText" placeholder="输入标签名称" />
      </u-modal>
    </view>
  </view>
  <view class="max-h-200px tag-list-box">
    <template v-for="(item,index) in props.tagList" :key="index">
      <view @click="handlerTagItemClick(item)" class="tag-item" :class="{active: selectTag.find(it => it.value === item.value)}">{{item.label}}</view>
    </template>
  </view>
</view>
</template>

<style lang="scss">
.tag-select{
  .tag-selected-box{
    border: 1px solid #efefef;
    border-radius: 4px;
    margin-bottom: 10px;
  }
  .tag-list-box{

  }
  .tag-item{
    display: inline-block;
    padding: 2px 8px;
    border-radius: 4px;
    margin: 2px 4px;
    background-color: #efefef;
    text-align: center;
    min-width: 40px;
    &.active{
      background-color: #33D89933;
    }
  }
}
</style>